<script setup>
import { reactive, ref, onUnmounted } from "vue";
import { useUsers } from "@/store/users.js";
import { useRouter } from "vue-router";
import {
  phoneRules,
  useSubmitForm,
} from "../../composition/loginVerification/validate";
import * as api from "@/api/user";
import { ElMessage } from "element-plus";
//引入loding加载
import { ElLoading } from "element-plus";
const phoneFormRef = ref();
//定义编程时导航
let route = useRouter();

//定义pinia
let useStore = useUsers();
let loadingInstance = null;
let validateSuccess = () => {
  //发起loding
  loadingInstance = ElLoading.service({
    // lock: true,
    text: "加载中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, .8)",
  });
  //发起登入请求
  verificationCode(phoneRuleForm.phoneverification);
}; //手机号发送成功验证函数
let verificationCode = async (n) => {
  try {
    let res = await api.loginSmsApi(n);
    // console.log(res.data.token)
    //页面跳转
    // route.push("/home")
    //存储信息
    let r = res.data.token;
    s.set("cgToken", r);
    useStore.$patch({
      userInfo: res.data.userInfo,
    });
    route.push("/home");
    ElMessage({
      message: "登入成功",
      type: "success",
    });
    loadingInstance.close();
  } catch (e) {
    console.log(e);
    loadingInstance.close();
  }
};
//存储封装
let s = {
  set(key, value) {
    sessionStorage.setItem(key, JSON.stringify(value));
  },
  get(key) {
    return sessionStorage.getItem(key);
  },
};
//表单校验失败,回调的方法
let validateFailed = () => {
  console.log("校验失败");
};
//点击登入
let phoneForm = useSubmitForm(validateSuccess, validateFailed);
//注入表单数据
const phoneRuleForm = reactive({
  phone: "159508124",
  phoneverification: "",
});
//定义切换函数
const emits = defineEmits(["backComponent"]);
let send = () => {
  emits("backComponent", "celliphone");
};

//短信登入流程
//定义点击发送文字
let desc = ref("点击发送短信");
//输入手机h 获取短信登入
//短信验证码需要倒计时
//处理用户频繁点击的问题
//利用开关的思维
let isClick = ref(false);
let timerDownInterval = null;
let clickSend = async () => {
  if (!isClick.value) {
    //发送请求
    try {
      let res = await api.loginSmsCodeApi(phoneRuleForm.phone);
      if (res.data.state) {
        //发送成功我们就开始验证手机验证码
        timerDownInterval = timeDown(
          60,
          desc,
          "秒后重新发送",
          "点击发送短信",
          () => {
            //让点击状态恢复到未点击
            isClick.value = false;
          }
        );
        ElMessage({
          message: "短信验证码发送成功",
          type: "success",
        });
      }
    } catch (e) {
      //出现错误就将开关关闭
      isClick.value = false;
      ElMessage({
        message: "短信验证码发送失败",
        type: "error",
      });
      return;
    }
  }
  //标记被点击了
  isClick.value = true;
};
//倒计时的方法
//padStart(不足3为,就补0)
//只能给字符串补齐
let timeDown = (timeCount = 5, param, msg, endMsg, cb) => {
  let count = timeCount;
  param.value = count.toString().padStart(2, 0) + msg;
  let timer = setInterval(() => {
    count--;
    param.value = count.toString().padStart(2, 0) + msg;
    if (count <= 0) {
      clearInterval(timer);
      param.value = endMsg;
      cb && cb();
      return;
    }
  }, 1000);
  //返回定时器的引用
  return timer;
};
//组件卸载的钩子
onUnmounted(() => {
  if (timerDownInterval) clearInterval(timerDownInterval);
});

//输入短信验证码，进行登入请求
</script>

<template>
  <el-form
    ref="phoneFormRef"
    :model="phoneRuleForm"
    status-icon
    :rules="phoneRules"
    label-width="70px"
  >
    <i class="cornermark iconfont icon-diannaojiaobiao" @click="send"></i>
    <el-form-item label="手机号" prop="phone" class="public-form-item">
      <el-input
        v-model="phoneRuleForm.phone"
        type="text"
        autocomplete="off"
        maxlength="11"
      />
      <span class="captha-svg" @click="clickSend">{{ desc }}</span>
    </el-form-item>
    <el-form-item label="验证码" prop="phoneverification">
      <el-input
        v-model="phoneRuleForm.phoneverification"
        type="text"
        autocomplete="off"
        maxlength="6"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="phoneForm(phoneFormRef)"
        >登入</el-button
      >
    </el-form-item>
  </el-form>
</template>

<style scoped lang="less">
.el-button {
  background: linear-gradient(90deg, #1596fb, #002dff);
  width: 340px;
}
//定义角标样式
.cornermark {
  font-size: 80px;
  color: #fff;
  position: absolute;
  right: -1px;
  top: -1px;
  cursor: pointer;
  opacity: 0.7;
}
.el-input {
  height: 45px;
}
</style>
